package com.yt.sys.api.client;

import com.alipay.api.AlipayApiException;
import com.yt.common.constant.Result;
import com.yt.sys.common.config.AlipayConfig;
import com.yt.sys.common.utils.AlipaySignatureUtil;
import com.yt.sys.models.service.IPaymentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;

/**
 * 支付宝支付接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/alipay")
@Api(value = "AlipayApiController", tags = "支付宝支付接口")
public class AlipayApiController {

    @Resource
    private AlipayConfig alipayConfig;

    // 注入账单服务
    @DubboReference
    private com.yt.phone.models.service.IBillService billService;
    
    // 注入支付订单服务
    @DubboReference
    private IPaymentOrderService paymentOrderService;
    
    // 注入用户服务
    @DubboReference
    private com.yt.phone.models.service.IUserService userService;

    /**
     * 发起支付 (支持GET和POST请求)
     *
     * @param userId      用户ID
     * @param totalAmount 订单总金额
     * @param subject     订单标题
     * @param body        订单描述
     * @return 支付页面表单
     */
    @ApiOperation("发起支付")
    @RequestMapping(value = "/pay", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html")
    public String pay(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String totalAmount,
            @RequestParam(required = false) String subject,
            @RequestParam(required = false) String body,
            HttpServletRequest request) {
        try {
            // 如果通过@RequestParam没有获取到参数，则尝试从request中获取
            if (userId == null) {
                String userIdStr = request.getParameter("userId");
                if (userIdStr != null) {
                    userId = Long.valueOf(userIdStr);
                }
            }
            if (totalAmount == null) {
                totalAmount = request.getParameter("totalAmount");
            }
            if (subject == null) {
                subject = request.getParameter("subject");
            }
            if (body == null) {
                body = request.getParameter("body");
            }
            
            // 参数验证
            if (userId == null || totalAmount == null || subject == null || body == null) {
                return "缺少必要参数";
            }
            
            // 创建支付订单，获取系统生成的订单号
            String outTradeNo = paymentOrderService.createPaymentOrder(userId, Double.valueOf(totalAmount));
            log.info("为用户ID {} 创建支付订单，订单号: {}", userId, outTradeNo);
            
            String result = alipayConfig.pay(outTradeNo, totalAmount, subject, body);
            return result;
        } catch (AlipayApiException e) {
            log.error("支付宝支付请求异常", e);
            return "支付请求失败";
        } catch (Exception e) {
            log.error("创建支付订单异常", e);
            return "支付请求失败";
        }
    }

    /**
     * 支付宝异步通知接口
     *
     * @param params 异步通知参数
     * @return 处理结果
     */
    @ApiOperation("支付宝异步通知接口")
    @PostMapping("/notify")
    public String notify(@RequestParam Map<String, String> params) {
        log.info("收到支付宝异步通知: {}", params);
        
        try {
            // 1. 验证签名
            boolean verifyResult = AlipaySignatureUtil.verifySignature(params);
            if (!verifyResult) {
                log.error("支付宝异步通知签名验证失败: {}", params);
                return "fail";
                }
            
            // 2. 处理业务逻辑
            // 获取商户订单号
            String outTradeNo = params.get("out_trade_no");
            // 获取支付宝交易号
            String tradeNo = params.get("trade_no");
            // 获取交易状态
            String tradeStatus = params.get("trade_status");
            // 获取订单金额
            String totalAmount = params.get("total_amount");
            
            // 3. 更新订单状态
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                // 根据订单号查询支付订单
                com.yt.sys.models.entity.PaymentOrder paymentOrder = paymentOrderService.getPaymentOrderByOrderNo(outTradeNo);
                if (paymentOrder == null) {
                    log.error("未找到支付订单，订单号: {}", outTradeNo);
                    return "fail";
                }
                
                // 获取用户ID和金额
                Long userId = paymentOrder.getUserId();
                Double amount = paymentOrder.getAmount();
                
                log.info("支付成功，用户ID: {}, 订单号: {}, 支付金额: {}", userId, outTradeNo, amount);
                
                // 更新支付订单状态为已支付
                boolean updateResult = paymentOrderService.updatePaymentOrderStatus(outTradeNo, 1);
                
                if (!updateResult) {
                    log.error("支付订单状态更新失败，订单号: {}", outTradeNo);
                    return "fail";
                }
                
                // 增加用户余额
                try {
                    com.yt.phone.models.dto.UserDTO user = userService.selectById(userId);
                    if (user != null) {
                        // 增加用户预存余额
                        Double currentReadyAmount = user.getReadyAmount() != null ? user.getReadyAmount() : 0.0;
                        user.setReadyAmount(currentReadyAmount + amount);
                        boolean userUpdateResult = userService.updateById(user);
                        
                        if (userUpdateResult) {
                            log.info("用户余额更新成功，用户ID: {}, 增加金额: {}, 当前余额: {}", userId, amount, user.getReadyAmount());
                        } else {
                            log.error("用户余额更新失败，用户ID: {}", userId);
                            return "fail";
                        }
                    } else {
                        log.error("未找到用户，用户ID: {}", userId);
                        return "fail";
                    }
                } catch (Exception e) {
                    log.error("更新用户余额异常，用户ID: {}", userId, e);
                    return "fail";
                }
                
                log.info("支付处理成功，订单号: {}, 用户ID: {}, 支付金额: {}, 支付方式: 支付宝", outTradeNo, userId, amount);
                return "success";
            }
        } catch (Exception e) {
            log.error("处理支付宝异步通知异常", e);
            return "fail";
        }
        
        return "success";
    }

    /**
     * 支付宝同步返回接口
     *
     * @param params 同步返回参数
     * @return 支付结果页面
     */
    @ApiOperation("支付宝同步返回接口")
    @GetMapping("/return")
    public String returnUrl(@RequestParam Map<String, String> params) {
        // 验证签名
        // 处理业务逻辑
        log.info("收到支付宝同步返回: {}", params);
        return "支付成功页面";
    }
}